import React, { useState, useEffect } from 'react';
import { LockTwoTone, UserOutlined, SafetyOutlined } from '@ant-design/icons';
import { history, Link, router } from 'umi';
import { Alert, message, Row, Col, Button } from 'antd';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { drawCode, Verification } from '@/utils/utils';
import config from '../../../config';
import Api from '../../../api';
import md5 from 'md5';
import styles from './index.less';
import logo from '../../../assets/logo.svg';

const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login = (props) => {
  const {
    location: { query },
  } = props;
  const [loading, setLoading] = useState(false);
  const [code, setCode] = useState('');

  useEffect(() => {
    const token = sessionStorage.getItem('TOKEN');

    if (query.isback) {
      sessionStorage.setItem('ISBACK', query.isback);
    }
    if (query.token) {
      sessionStorage.setItem('TOKEN', query.token);
      GetOfficialList();
      return;
    }
    if (query.auth_code && !token) {
      //根据企微code获取token
      Api.User.GetWorkWechatWebToken({
        code: query.auth_code,
        workWechatAppID: config.workwechatappid,
      }).then((res) => {
        if (res.Ret === 0 && res.Data) {
          sessionStorage.setItem('TOKEN', res.Data.Token);
          GetOfficialList();
        } else {
          message.error(res.Msg || '您的企微没有权限');
        }
      });
    }
    setCode(drawCode());
  }, []);

  const GetOfficialList = async () => {
    await Api.User.GetOfficialList({}).then((res) => {
      setLoading(false);
      if (res.Ret === 0 && res.Data.length) {
        sessionStorage.setItem('USER', JSON.stringify(res.Data[0])); // 机构ID
        sessionStorage.setItem('USERLIST', JSON.stringify(res.Data)); // 机构ID
        history.push('/content/lanMu');
      } else {
        message.error(res.Msg || '您没有后台权限！');
      }
    });
  };

  const handleSubmit = (values) => {
    const ts = Math.round(new Date().getTime() / 1000);
    // setLoading(true);
    // Api.User.GetWebToken({
    //   uxcode: values.userName,
    //   md5pwd: md5(values.password),
    //   appid: config.appId,
    //   ts,
    //   md5ts: md5(config.appsecret + ts),
    // }).then((res) => {
    //   if (res.Ret === 0) {
    //     sessionStorage.setItem('TOKEN', res.Data.Token);
    //     GetOfficialList();
    //   } else {
    //     setLoading(false);
    //     message.error(res.Msg);
    //   }
    // });
    if (values.userName === 'admin' && values.password === '123456') {
      history.push('/content/lanMu');
    } else {
      message.error('请输入正确的账号与密码');
    }
  };

  // 企微扫码登录
  function wxwokeLogin() {
    const wx_appId = config.wx_appId;
    const baseUrl = config.url + '/wgwpc';
    const redirect_uri = encodeURIComponent(baseUrl);
    const userType = 'member';
    sessionStorage.clear()
    window.location.href =
      'https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=' +
      wx_appId +
      '&redirect_uri=' +
      redirect_uri +
      '&state=&usertype=' +
      userType +
      '';
  }

  if (query.isback) {
    return '';
  }
  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/">
              <img alt="logo" className={styles.logo} src={logo} />
              <span className={styles.title}>Hi 卡夫卡</span>
            </Link>
          </div>
          <div className={styles.desc}></div>
        </div>
        <div className={styles.main}>
          <ProForm
            submitter={{
              // render: (_, dom) => dom.pop(),
              searchConfig: {
                submitText: '登录',
              },
              submitButtonProps: {
                loading,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
              // 完全自定义整个区域
              render: (props, doms) => {
                return [
                  <Button
                    type="primary"
                    key="submit"
                    loading={loading}
                    onClick={() => props.form?.submit?.()}
                  >
                    登录
                  </Button>,
                  <Button type="primary" key="rest" loading={loading} onClick={() => wxwokeLogin()}>
                    企微扫码登录
                  </Button>,
                ];
              },
            }}
            onFinish={async (values) => {
              handleSubmit(values);
            }}
          >
            {/* <LoginMessage
            content='账户或密码错误（admin/ant.design)'
          /> */}
            <>
              <ProFormText
                name="userName"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder="用户名"
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockTwoTone className={styles.prefixIcon} />,
                }}
                placeholder="密码"
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
              <Row gutter={24}>
                <Col span={15}>
                  <div style={{ width: '170px' }}>
                    <ProFormText
                      name="code"
                      fieldProps={{
                        size: 'large',
                        prefix: <SafetyOutlined className={styles.prefixIcon} />,
                      }}
                      placeholder="请输入验证码"
                      rules={[
                        {
                          // validator: Verification,
                          validator: (rule, value, callback) => {
                            if (!value) {
                              callback('请输入验证码');
                              return;
                            }
                            if (value.toLowerCase() !== code.toLowerCase()) {
                              callback('验证码错误');
                            } else {
                              callback();
                            }
                          },
                        },
                      ]}
                    />
                  </div>
                </Col>
                <Col span={9}>
                  <img id="code_img" alt="验证码" onClick={() => setCode(drawCode())} />
                </Col>
              </Row>
            </>
          </ProForm>
          <canvas width="100" height="40" id="verifyCanvas" />
        </div>
      </div>
    </div>
  );
};

export default Login;
